'use strict';
import React from "react";
import {ImageBackground, StyleSheet, Text, TouchableOpacity, View} from "react-native";
import Container from "../../component/common/Container";
import NavigationBar from "../../component/navigation/NavigationBar";
import ImageView from "../../component/common/ImageView";
import ListView from "../../component/list/ListView";
import {HorizontalLine} from "../../component/common/CommonLine";
import SpinnerLoading from "../../component/common/SpinnerLoading";

class SubjectDetail extends React.Component {

    constructor(props) {
        super(props);
        this.params = this.props.navigation.state.params;
        this.subject_id = this.params.subject_id;
        this.state = {
            data: {},
            ready: false,
            newsList: [],
            subjectInfo: {},
        };
        this.page = 1;
        this.limit = 10;
    }

    componentDidMount() {
        // this.requestDataSource();
        this.requestNewsDataSources();
    }

    requestDataSource = async () => {
        const data = {
            subject_id: this.subject_id,
            type: 'main',
        };
        const result = await Services.post(ServicesApi.SUBJECT_DETAIL, data);
        // console.log('专题详情返回------------->',result);
        if (result.code === StatusCode.SUCCESS_CODE) {
            this.setState({data: result.data})
        }
    };

    requestNewsDataSources = async () => {
        // let url = ServicesApi.QUERY_TOP;
        let url = ServicesApi.SUBJECT_DETAIL;
        let data = {
            subject_id: this.subject_id,
            type: 'main',
            page: this.page,
            limit: this.limit,
        };
        const result = await Services.post(url, data);
        let dataSource = [];
        if (result.code === StatusCode.SUCCESS_CODE) {
            dataSource = result.data.subinforVOs;
            this.setState({
                subjectInfo: result.data
            });
            if (this.page === 1) {
                this.setState({newsList: dataSource})
            } else if (this.page > 1 && dataSource.length !== 0) {
                let oldData = this.state.newsList.slice();
                oldData = oldData.concat(dataSource);
                this.setState({newsList: oldData});
            }
        }
        this.setState({ready: true});
        this._listViewRef && this._listViewRef.stopRefresh();
        this._listViewRef && this._listViewRef.stopEndReached({allLoad: dataSource.length < this.limit});

    };

    renderItem = ({item}) => {
        let base_host = ServicesApi.QI_NIU_LINK;
        if (item.data_type) {
            base_host = item.data_type === 'local' ? ServicesApi.QI_NIU_LINK : ServicesApi.THIRD_LINK;
        }
        return (
            <TouchableOpacity
                style={[styles.newsItem]}
                onPress={() => this._onPressNewsItem(item)}
            >
                <View style={styles.newsItemLeft}>
                    <Text style={styles.newsTitle} numberOfLines={2}>{item.information_title}</Text>
                    <Text
                        style={styles.newsTime}>{Moment(item.publish_time).format('MM月DD日 HH:mm')}</Text>
                </View>
                <View style={styles.itemCover}>
                    <ImageView
                        resizeMode={'cover'}
                        style={[styles.newsImg]}
                        source={item.cover_url ? {uri: base_host + item.cover_url} : Images.img_shop_default}
                    />
                    {item.article_type > 1 && <ImageView
                        tintColor={'#fff'}
                        resizeMode={'cover'}
                        style={[styles.videoPlayIcon]}
                        source={Images.icon_video_play}
                    />}
                </View>
            </TouchableOpacity>
        );
    };

    _onPressNewsItem = (item) => {
        let component = item.article_type > 1 ? 'VideoDetail' : 'ArticleDetails';
        RouterHelper.navigate('', component, {information_id: item.information_id});
    };

    _onRefresh = () => {
        this.page = 1;
        this.requestNewsDataSources();
    };

    _onEndReached = () => {
        this.page++;
        this.requestNewsDataSources();
    };

    _renderItemSeparator = () => {
        return (
            <HorizontalLine style={styles.horLine}/>
        )
    };

    _keyExtractor = (item, index) => {
        return `item${index}`
    };

    _captureRef = (v) => {
        this._listViewRef = v
    };

    renderListHeaderComponent = () => {
        let {subjectInfo} = this.state;
        return (
            <View style={styles.listHeaderContent}>
                <ImageBackground
                    style={styles.headBackImage}
                    resizeMode={'cover'}
                    source={subjectInfo.subject_picture ? {uri: `${ServicesApi.QI_NIU_LINK}${subjectInfo.subject_picture}`} : null}
                >
                    <Text numberOfLines={1} style={styles.imgTitle}>{subjectInfo.subject_title}</Text>
                </ImageBackground>
                <Text style={styles.context}>{subjectInfo.subject_desc}</Text>
                <HorizontalLine style={styles.horLine}/>
            </View>
        );
    };


    render() {
        let {newsList, ready} = this.state;
        let pageTitle = this.params.pageTitle || '专题';
        return (
            <Container>
                <NavigationBar
                    title={pageTitle}
                />
                {ready ?
                    <ListView
                        ref={this._captureRef}
                        initialRefresh={false}
                        enableLoadMore={true}
                        enableRefresh={true}
                        data={newsList}
                        keyExtractor={this._keyExtractor}
                        renderItem={this.renderItem}
                        ItemSeparatorComponent={this._renderItemSeparator}
                        onRefresh={this._onRefresh}
                        onEndReached={this._onEndReached}
                        ListHeaderComponent={this.renderListHeaderComponent}
                    />
                    : <SpinnerLoading/>
                }
            </Container>
        );
    }
}

const itemWidth = SCREEN_WIDTH * 0.282;
const itemHeight = itemWidth * 0.666;

const styles = StyleSheet.create({
    scroll: {
        flex: 1,
    },
    listHeaderContent: {},
    headBackImage: {
        width: SCREEN_WIDTH,
        height: SCREEN_WIDTH * 0.42,
    },
    imgTitle: {
        position: 'absolute',
        bottom: 13,
        left: 15,
        fontSize: FontSize(14),
        color: "#ffffff",
    },
    context: {
        marginTop: 20,
        marginBottom: 10,
        color: "#9d9d9d",
        marginHorizontal: 15,
        fontSize: FontSize(14),
    },
    horLine: {
        marginVertical: 10,
    },
    newsItem: {
        flexDirection: 'row',
        marginHorizontal: 15,
    },
    newsItemLeft: {
        justifyContent: 'space-between',
        flex: 1,
        marginRight: 30,
        alignSelf: 'stretch',
    },
    newsTitle: {
        marginTop: 3,
        lineHeight: 20,
        color: "#4a4a4a",
        paddingVertical: 0,
        fontSize: FontSize(14),
    },
    newsTime: {
        fontSize: FontSize(12),
        color: "#929292",
    },
    newsImg: {
        borderRadius: 7,
        width: itemWidth,
        height: itemHeight,
    },
    itemCover: {
        alignItems: 'center',
        justifyContent: 'center',
    },
    videoPlayIcon: {
        position: 'absolute',
    },
});

export default SubjectDetail